package com.example.java_chatroom1.controller;

import com.example.java_chatroom1.model.Result;
import com.example.java_chatroom1.model.User;
import com.example.java_chatroom1.server.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/registry")
    public Result<Boolean> registry(String userName,String password,String repassword) {
        log.info("userName:" + userName + " password:" + password);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)
        ||!StringUtils.hasLength(repassword)) {
            return Result.fail(404,false,"账号或者密码为空");
        }
        if (!password.equals(repassword)) return Result.fail(404,false,"两次输入的密码不一致");
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        try {
            int ret = userService.registry(user);
            if (ret <= 0) {
                return Result.fail(500,false,"注册失败，请联系管理员");
            }else {
                return Result.success(true);
            }
        }catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            return Result.fail(404,false,"该用户已存在！");
        }
    }

    @RequestMapping("/login")
    public Result<Boolean> login(String userName, String password, HttpServletRequest request) {
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail(404,false,"账号或者密码为空");
        }
        User user = userService.queryByName(userName);
        if (user == null || user.getUserId() < 0) {
            return Result.fail(404,false,"抱歉，该用户不存在！");
        }else {
            if (!password.equals(user.getPassword())) {
                return Result.fail(404,false,"账号或者密码错误");
            }else {
                HttpSession session = request.getSession();
                user.setPassword("");
                session.setAttribute("user",user);
                return Result.success(true);
            }
        }
    }

    @RequestMapping("/getUserInfo")
    public Result<User> getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute("user");
        return Result.success(user);
    }
}
